<template>
  <div>
    <div>
      <!--    搜索框-->
      <div class="mt-4">
        <el-input
            v-model="input"
            placeholder="在此输入想查询的信息"
            class="input-with-select"
            @input="filterSearch"
        >
          <template #prepend>
            <el-select v-model="select" placeholder="选择" style="width: 115px">
              <el-option label="名称" value="1" />
            </el-select>
          </template>
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <!--      添加数据、批量删除-->
        <el-button type="primary" plain class="bt1" @click="handleAdd"><el-icon><CirclePlusFilled /></el-icon>添加原材料</el-button>
        <el-button type="danger" plain @click="handleDelList" v-if="multipleSelection.length>0"><el-icon><RemoveFilled /></el-icon>批量删除</el-button>
        <el-button type="primary" :icon="FolderAdd" @click="handleAddExcel"
                   style="margin-left: 20px;">导入原材料数据
        </el-button>
        <el-button type="primary" :icon="FolderChecked" @click="handleExcel"
                   style="margin-left: 20px;">导出原材料excel
        </el-button>
        <el-button type="primary" :icon="FolderChecked" @click="handleMuban"
                   style="margin-left: 20px;">下载excel模板
        </el-button>
      </div>
    </div>
    <!--    表格-->
    <el-table
        ref="tableRef"
        row-key="id"
        :data="tableData"
        style="width: 100%"
        @sort-change="handleSortChange"
        empty-text="暂无数据"
        @selection-change="handleSelectionChange"
    >
      <!--      选择列-->
      <el-table-column type="selection" width="60"></el-table-column>
      <!--      编号列-->
      <el-table-column prop="mid" label="编号" width="100" sortable></el-table-column>
      <!--      名称列-->
      <el-table-column prop="mname" label="名称" width="200" />
      <!--      数量列-->
      <el-table-column prop="mnum" label="数量(g)" width="200" sortable />
      <!--      删除编辑列-->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
              size="small"
              @click="handleEdit(scope.row)"
          >编辑</el-button
          >
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
          >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--    分页功能-->
    <div class="demo-pagination-block">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          background
          layout="total, prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
      />
    </div>
    <!--表单数据-->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" style="width: 400px">
      <el-form :model="tableform">
        <!--        名称-->
        <el-form-item label="名称">
          <el-input v-model="tableform.mname" style="width: 300px"/>
        </el-form-item>
        <el-form-item label="数量">
          <div class="mt-4">
            <el-button @click="jian">-</el-button>
            <el-input v-model="tableform.mnum" style="margin-left: 12px"/>
            <el-button @click="jia" style="margin-left: 12px">+</el-button>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" style="margin-left: 145px">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>


  <!-- excel上传界面 -->
  <el-dialog v-model="dialogFileVisible" title="excel上传" style="margin-top: 20px">
    <el-upload
        ref="upload"
        class="upload-demo"
        drag
        action="http://192.168.166.182:8080/material/addMaterialExcel"
        :limit="1"
        :on-exceed="handleExceed"
        :auto-upload="false"
        :before-upload="beforeUpload"
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">
        拖拽上传或者 <em>点击选择文件</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">

        </div>
      </template>
    </el-upload>
    <template #footer>
    <span class="dialog-footer1">
      <el-button type="primary" @click="submitUpload">
        上传
      </el-button>
    </span>
    </template>
  </el-dialog>

</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import { Search, FolderChecked, FolderAdd} from '@element-plus/icons-vue'
import type { TableColumnCtx, TableInstance } from 'element-plus'
import { reactive,computed } from "vue";
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import axios from "axios";

// 表格数据
const tableData = ref([])
const currentPage = ref(1); //定义当前页码初始值为1
const pageSize = ref(12); //定义每页显示的数据条数为10
let total = ref(0); //初始化数据总条数

// 使用axios.get()方法获取用户列表
// 在组件挂载后执行回调函数
onMounted(() => {
  getData()
})

// 获取当前页数据
const getData = () => {
  axios.get("http://192.168.166.182:8080/material/getAll",{
    params: {
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
  }).then(response => {
    console.log(response.data)
    tableData.value  = response.data.records;
    total.value = response.data.total;
  }).catch(error => {
    console.error(error);
  })
}

//页数改变
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getData();
}

//排序
const handleSortChange = (sortData) => {
  //解构sortData参数，得到prop和order两个属性
  const { prop,order } = sortData;
  //使用sort方法对当前页面数据进行排序，并更新其值
  tableData.value = tableData.value.sort((a,b) => {
    if(order === 'ascending') { //升序
      return a[prop] === b[prop] ? a.mid - b.mid : a[prop] > b[prop] ? 1 : -1;
    } else { //降序
      return a[prop] === b[prop] ? a.mid - b.mid : a[prop] < b[prop] ? 1 : -1;
    }
  });
}

const input = ref('') //初始化搜索输入框
const select = ref('') //初始化搜索选择栏
//搜索框搜查
const filterSearch = (val) => {
  //根据姓名搜索
  if(select.value === "1") {
    //搜索框有输入
    if(val.length > 0) {
      axios.get(`http://192.168.166.182:8080/material/getMaterial/${val}`,{
        params: {
          pageNo: currentPage.value,
          pageSize: pageSize.value
        }
      }).then(response => {
        console.log(response.data)
        tableData.value = response.data.records;
        total.value = response.data.total;
      }).catch(error => {
        console.error(error)
      })
    } else { //搜索框无输入
      getData()
    }
  }
}

const dialogFormVisible = ref(false); //初始化弹窗不显示
let tableform = ref({}); //初始化弹窗表单数据
let dialogType = ref('add'); //初始化弹窗类型为增加弹窗
const dialogTitle = computed(() => { //设置弹窗的标题
  return dialogType.value === 'add' ? '新增数据' : '编辑数据';
})
//添加数据按钮事件
const handleAdd = () => {
  dialogFormVisible.value = true;
  dialogType.value = 'add';
  tableform.value = { num:0 };
}

//编辑数据按钮事件
const handleEdit = (row) => { //row为当前行的数据
  dialogFormVisible.value = true;
  dialogType.value = 'edit';
  tableform.value = {...row};
}

//删除数据方法
const delrow = (row) => { //定义一个函数，用于删除某行数据
  const memberId = parseInt(row.mid);
  // 发送 HTTP DELETE 请求来删除用户
  axios.delete(`http://192.168.166.182:8080/material/deleteMaterial/${memberId}`)
      .then(response => {
        // 处理删除成功后的逻辑，例如重新加载数据
        getData();
      }).catch(error => {
    // 处理错误
    console.error(error)
  })
}

//删除事件
const handleDelete = (row) => {// 处理删除按钮点击事件
  ElMessageBox.confirm(
      '您确定要删除名称为【' + row.mname + '】的数据吗?', '危险操作',
      {confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning',}
  )
      .then(() => {
        delrow(row)
        ElMessage({type: 'success', message: '完成删除！',})
      })
      .catch(() => {
        ElMessage({type: 'info', message: '取消删除!',})
      })
}

let multipleSelection = ref([]); //创建响应式变量，储存当前选中的数据行
//处理表格行选中状态变化的方法，val是当前选中的数据型数组
const handleSelectionChange = (val) => {
  multipleSelection.value = [];
  val.forEach(item => { //遍历选中的数据行数组
    multipleSelection.value.push(item.mid) //将选中的每一行数据加入数组中
  })
  console.log(multipleSelection.value)
}

//批量删除
const handleDelList = () => {
  ElMessageBox.confirm(
      '您确定要删除选择的数据嘛？',
      '危险操作',
      {confirmButtonText:'确定',cancelButtonText:'取消',type:'warning',}
  ).then(() => {
    const memberIds = multipleSelection.value.map(Number);
    console.log(memberIds)
    axios.delete('http://192.168.166.182:8080/material/deleteMateritals/' + memberIds.join(','))
        .then(response => {
          // 处理删除成功后的逻辑，例如重新加载数据
          getData();
          ElMessage({type:'success',message:'完成删除！',})
        }).catch(error => {
      console.error(error);
      ElMessage({ type: 'error', message: '删除失败！' });
    });
  }).catch(() => {
    ElMessage({type:'info',message:'取消删除！',})
  })
}

//确定添加数据
const onSubmit = () => {
  dialogFormVisible.value = false;
  if(dialogType.value === 'add') {
    const newMember = {...tableform.value}
    console.log(newMember)
    axios.post('http://192.168.166.182:8080/material/addMaterial',newMember)
        .then(response => { // 处理成功响应
          console.log(response)
          if(!response.data) ElMessage({ type: 'error', message: '该原材料已存在！请勿重复添加！' });
          else {
            ElMessage({type:'success',message:'添加成功！',})
            getData(); // 在添加数据后调用获取数据的方法
          }
        }).catch(error => { // 处理错误
      console.log(error);
    })
  } else {
    // 创建一个副本来保存更新后的用户信息
    const updateMember = {...tableform.value}
    // 发送 HTTP PUT 请求来更新用户信息
    axios.put(`http://192.168.166.182:8080/material/updateNum`,updateMember)
        .then(reponse => {
          // 处理成功响应
          ElMessage({type:'success',message:'修改成功！'})
          // 重新获取数据，更新表格显示
          getData()
        }).catch(error => {
      // 处理错误
      console.error('更新失败！')
      console.error(error)
    })
  }
}

// 表单的增加按钮和删除按钮
const jia = () => {
  if(tableform.value.mnum == null) tableform.value.mnum = 0;
  tableform.value.mnum = tableform.value.mnum + 1;
}
const jian = () => {
  if(tableform.value.mnum > 0) tableform.value.mnum = tableform.value.mnum - 1;
}


// excel导入导出
const dialogFileVisible = ref(false);
let upload = ref(null);

const handleAddExcel = () =>{
  dialogFileVisible.value = true;
}

const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

const beforeUpload = (file) => {
  const allowedTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  const isAllowedType = allowedTypes.includes(file.type);
  if (!isAllowedType) {
    ElMessage.error('只能上传Excel表格文件');
  }
  return isAllowedType;
}

const submitUpload = () => {
  if(upload.value.submit()){
    ElMessage.success('导入成功');
    dialogFileVisible.value = false;
    upload = null;
  }
}

//导出为excel
const handleExcel = () =>{
  var url = "http://192.168.166.182:8080/material/getMaterialExcel";
  axios({
    method: 'get',
    url: url,
    responseType: 'blob'
  })
      // axios.get('http://192.168.140.182:8080/student/getExcel')
      .then(res => {
        console.log(res)
        // const link = document.createElement("a");
        // const blob = new Blob([res], {
        //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        // });
        // link.style.display = "none";
        // link.href = URL.createObjectURL(blob);
        // link.setAttribute("download", `学生数据.xlsx`);
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        const content = res.data
        const blob = new Blob([content], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = '原材料数据.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }

      })
      .catch(error => {
        console.error(error);
      });
}

//导出模板
const handleMuban = () =>{
  var url = "http://192.168.166.182:8080/material/getMaterialExcelMb";
  axios({
    method: 'get',
    url: url,
    responseType: 'blob'
  })
      // axios.get('http://192.168.140.182:8080/student/getExcel')
      .then(res => {
        console.log(res)
        // const link = document.createElement("a");
        // const blob = new Blob([res], {
        //   type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
        // });
        // link.style.display = "none";
        // link.href = URL.createObjectURL(blob);
        // link.setAttribute("download", `学生数据.xlsx`);
        // document.body.appendChild(link);
        // link.click();
        // document.body.removeChild(link);
        const content = res.data
        const blob = new Blob([content], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const fileName = '原材料数据模板.xlsx'
        if ('download' in document.createElement('a')) { // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else { // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }

      })
      .catch(error => {
        console.error(error);
      });
}
</script>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
.demo-pagination-block {
  margin-top: 10px;
}
.mt-4 {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.bt1 {
  margin-left: 15px;
}
</style>
